<?php


namespace tools\lib\main\model;

use tools\lib\main\Common;

/**
 * 创建字典
 * Class Dictionary
 * @package app\common\command\create
 */
class Data extends Common
{
    public function template()
    {

        $result = $this->getFields();

        $template = <<<EOT
<?php

{$this->getFileNamespace()}

use common\data\DataSetter

class {$this->className()} extends DataSetter
{
    {$result['field']}
    
    {$result['method']}
}
EOT;
        return $template;
    }

    public function getFields()
    {
        $columns = tableColumns($this->parameter->getName());

        $concatPro = function ($field, $type) {
            return <<<EOF
/**
     * @var {$type}
     */           
    private \${$field};
    
    
EOF;
        };

        $concatMethod = function ($field, $type) {

            $method = transToPascal($field);

            if ($type==="integer"){
                $return="return intval(\$this->$field);";
            }else{
                $return="return \$this->$field;";
            }

            return <<<EOF
/**
     * @param \${$field}
     * @return \$this
     */
    public function set{$method}(\${$field})
    {
        \$this->$field = \${$field};
    
        return \$this;
    }
    
    /**
     * @return {$type}
     */
    public function get{$method}()
    {
        $return
    }
    
    
EOF;
        };

        $fields = '';
        $methods = '';
        if ($columns) {
            foreach ($columns as $column) {
                if (in_array($column['Field'], [
                    'create_time',
                    'update_time',
                    'delete_time',
                ])) {
                    continue;
                }

                if (preg_match('/int/', $column['Type'])) {
                    $type = "integer";
                } elseif (preg_match('/char/', $column['Type'])) {
                    $type = "string";
                } else {
                    $type = "string";
                }

                $fields .= $concatPro($column['Field'], $type);

                $methods .= $concatMethod($column['Field'], $type);
            }
        }

        return [
            'field' => trim($fields),
            'method' => trim($methods),
        ];
    }
}